package licode.unisop.platform.adapter.web;

import licode.unisop.client.api.SopPlatformAuth;
import licode.unisop.client.info.SopIdInfo;
import licode.unisop.client.inter.HasAuthority;
import licode.unisop.client.utils.SopException;
import licode.unisop.client.utils.SopRequestParse;
import licode.unisop.client.utils.StringUtil;
import licode.unisop.client.vo.SopAuthPlatform;
import licode.unisop.platform.application.executor.SiPlatformExecutor;
import licode.unisop.platform.client.info.PlatSaveAssetIn;
import licode.unisop.platform.client.info.PlatformSaveIn;
import licode.unisop.provider.info.SiPlatformId;
import licode.unisop.types.AuthConst;
import licode.unisop.unilite.result.UniReturnResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 平台操作对外接口
 *
 * @author licode
 */
@Slf4j
@RestController
@UniReturnResult
@RequestMapping("/plat-api/v1/internal/platform")
public class PlatformAdapter {
    @Resource
    private HttpServletRequest request;

    @Resource
    private SopPlatformAuth sopPlatformAuth;

    @Resource
    private SiPlatformExecutor platformExecutor;

    public void checkCenterPlatform() {
        String platId = SopRequestParse.getPlatformId(request);
        String modalToken = SopRequestParse.getModalToken(request);
        SopAuthPlatform authPlat = sopPlatformAuth.fromId(SopIdInfo
                .builder().id(platId).build());
        if (null == authPlat) {
            throw new SopException(-1, "无效平台");
        }
        if (!AuthConst.SSO_MANAGER_PLATFORM_ID.equals(platId) ||
                !authPlat.getModelToken().equals(modalToken)) {
            throw new SopException(-1, "平台未认证");
        }
    }

    @RequestMapping(value = "/cache/update", method = RequestMethod.POST)
    public void updateCache(@RequestBody SiPlatformId platId) {
        platformExecutor.updateCache(platId);
    }

    /**
     * 保持平台信息
     * @param platform 平台信息
     */
    @PostMapping("/add")
    public String addPlatform(@RequestBody PlatformSaveIn platform) {
        checkCenterPlatform();
        platformExecutor.addPlatform(platform);
        return "ok";
    }

    @PostMapping("/update")
    public String updatePlatform(@RequestBody PlatformSaveIn platform) {
        checkCenterPlatform();
        platformExecutor.updatePlatform(platform);
        return "ok";
    }

    /**
     * 根据操作类型完成对资源的处理
     * @param assetIn 资源和操作类型
     */
    @PostMapping("/asset/save")
    public String saveAsset(@RequestBody PlatSaveAssetIn assetIn) {
        checkCenterPlatform();
        platformExecutor.saveAsset(assetIn);
        return "ok";
    }
}
